require("babel-polyfill");
import "./assets/style/main.scss";
import $ from "jquery";

const { User } = require("./lib/db");
const user = new User();

const displayMessage = (subject, body) => {
  console.log(subject, body);
};

$("#items").hide();
const showPage = () => {
  $("#login").hide();
  $("#items").show();

  /*
  const find = gun.user(user.is.pub).get("profile");
  find.on((data, key) => {
    //console.log(data, key, at, ev);
    Gun.node.is(data, async (v, k) => {
      console.log("data", v, k);
      var key = await find
        .get("trust")
        .get(user.pair().pub)
        .get(k + "profile")
        .then();
      var mix = await Gun.SEA.secret(
        await find.get("epub").then(),
        user.pair()
      );
      key = await Gun.SEA.decrypt(key, mix);
      var val = await Gun.SEA.decrypt(v, key);
      $("#" + k).val(val || v);
    });
  });
  */
};

$("#register").on("click", async e => {
  const result = await user
    .create($("#alias").val(), $("#pass").val())
    .catch(e => {
      displayMessage("Error", e.message);
      return;
    });
  if (!result) return;
  displayMessage("Success", "User " + result.alias + " created.");
  showPage();
});

$("#login").on("submit", async e => {
  e.preventDefault();
  const result = await user
    .auth($("#alias").val(), $("#pass").val())
    .catch(e => {
      displayMessage("Error", e.message);
      return;
    });
  if (!result) return;
  displayMessage("Success", "User " + result.alias + " authenticated.");
  showPage();
});

$("#items input").on("keyup", e => {
  if (!user.is) return;
  console.log("keyup", e);
  const id = $(e.currentTarget).attr("id");
  user
    .get("profile")
    .get(id)
    .secret($(e.currentTarget).val());

  user
    .get("profile")
    .get(id)
    .grant(user.is.pub);
});

/*
gun.get("mark").put({
  name: "Mark",
  email: "mark@gunDB.io"
});

gun.get("mark").on(function(data, key) {
  console.log("update:", JSON.stringify(data));
});
*/
